#include "tcpClient.h"
#include "logger.h"
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
#include "IpAddressPort.h"
#include "msg.h"
TcpClient::TcpClient(const IpAddressPort& IpAddressAndPort)
{
    m_sfd=socket(AF_INET,SOCK_STREAM,0);
    if(m_sfd==-1)
    {
        LOG_FATAL<<strerror(errno);
    }
    struct sockaddr_in saddr;
    saddr.sin_addr.s_addr=inet_addr(IpAddressAndPort.GetIpAddress().c_str());
    saddr.sin_family=AF_INET;
    saddr.sin_port=htons(IpAddressAndPort.GetPort());
    int res=connect(m_sfd,(struct sockaddr*)&saddr,sizeof(saddr));
    if(res==-1)
    {
        LOG_FATAL<<strerror(errno);
    }
    LOG_INFO<<"connect success";
}
TcpClient::~TcpClient()
{
    if(-1==close(m_sfd))
    {
        LOG_FATAL<<strerror(errno);
    }
}
int TcpClient::SendMsg(const std::string& msg)
{
    int numberOfSendByte=send(m_sfd,msg.c_str(),strlen(msg.c_str()),0);
    if(-1 == numberOfSendByte)
    {
        LOG_ERROR<<strerror(errno);
    }
    return numberOfSendByte;
}
Msg TcpClient::RecvMsg()
{
    char buff[LARGE_BUF_LEN]={0};
    int numberOfRecvByte=recv(m_sfd,buff,LARGE_BUF_LEN,0);
    if(-1==numberOfRecvByte)
    {
        LOG_ERROR<<strerror(errno);
    }
    return Msg{buff,numberOfRecvByte};
}

int TcpClient::GetSfd()const
{
    return m_sfd;
}
